package com.example.statistics.ui.product

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.KeyValue
import com.example.statistics.bean.ProductBean
import com.example.statistics.bean.ProductItemBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityresult.ActivityResult
import com.example.statistics.weight.ImageLayout
import com.example.statistics.weight.ItemLayout
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.model.HttpParams
import com.jhj.prompt.fragment.TimeFragment
import com.jhj.prompt.fragment.options.interfaces.OnTimeSelectedListener
import com.jhj.slimadapter.SlimAdapter
import kotlinx.android.synthetic.main.activity_base.*
import kotlinx.android.synthetic.main.activity_product_info_edit.*
import kotlinx.android.synthetic.main.layout_top_bar.view.*
import kotlinx.android.synthetic.main.list_item_product_price.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class ProductInfoEditActivity : BaseActivity() {
    private val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    val dataList = arrayListOf<KeyValue>()
    val adapter = SlimAdapter.creator()
    private var productInfoId = -1
    private var productName = ""
    override val title: String
        get() = "产品信息"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_product_info_edit)
        productInfoId = intent.getIntExtra(Constants.ID, -1)
        topBarRightText("保存") {
            if (top_bar.tv_top_bar_right.text == "保存") {
                commit()
            } else {
                top_bar.tv_top_bar_right.text = "保存"
                layout_display.visibility = View.GONE
                layout_edit.visibility = View.VISIBLE
            }
        }
        il_type.contentText = intent.getStringExtra(Constants.TYPE)
        il_type.onClick {
            il_type.contentText = if (il_type.contentText == "猪副") "牛副" else "猪副"
        }
        if (productInfoId == -1) {
            layout_display.visibility = View.GONE
            layout_edit.visibility = View.VISIBLE
            price()
        } else {
            layout_edit.visibility = View.GONE
            layout_display.visibility = View.VISIBLE
            top_bar.tv_top_bar_right.text = "编辑"
            httpGet<ProductBean>(UrlConfig.PRODUCT_INFO_DATA, config = {
                listParams = listOf("id" to productInfoId)
                isShowDialog = true
            }) {
                initInfo(it)
            }
        }
        detail()
    }

    private fun initInfo(bean: ProductBean?) {
        bean?.let {
            productName = it.factoryNo + it.productName
            val priceList = mutableListOf<KeyValue>()
            it.priceTrend.split(";").forEach { str ->
                if (str.contains("->")) {
                    val index = str.indexOf("->")
                    priceList.add(KeyValue(str.substring(0, index).trim(), str.substring(index + 2, str.length).trim()))
                }
            }
            dataList.addAll(priceList)
            price()
            var text = ""
            if (!it.productNo.isNullOrEmpty()) {
                text += "产品注册号：${it.productNo} "
            }
            if (!it.specification.isNullOrEmpty()) {
                text += if (it.specification.isNumber()) {
                    " 规格：${it.specification}Kg"
                } else {
                    " 规格：${it.specification}"
                }
            }
            //查看
            tv_title.text = it.factoryNo + it.productName
            tv_product_no.text = text
            tv_remark.text = it.remark
            val imageList = it.imageList?.map { UrlConfig.BASE_URL + it.path }
            if (!imageList.isNullOrEmpty()) {
                banner.setViewUrls(imageList.toList())
                banner.setOnBannerItemClickListener { index ->
                    imageDisplay(imageList, index)
                }
                banner.onClick { _ ->
                    imageDisplay(imageList)
                }
            }

            //编辑
            il_type.contentText = it.productType
            il_nation.contentText = it.nation
            il_company.contentText = it.company
            il_factory.contentText = it.factoryNo
            il_product_name.contentText = it.productName
            il_product_no.contentText = it.productNo
            il_specification.contentText = if (it.specification.isNumber()) {
                "${it.specification}Kg"
            } else {
                it.specification
            }
            il_remark.contentText = it.remark

            adapter.setDataList(it.productDetail.orEmpty())

            if (!imageList.isNullOrEmpty())
                layout_image.setImageList(imageList)
        }
    }

    private fun detail() {
        val dataList = mutableListOf<ProductItemBean>()
        adapter
                .register<ProductItemBean>(R.layout.list_item_product_detail) { injector, bean, position ->
                    injector
                            .with<ItemLayout>(R.id.il_date) {
                                if (bean.productDate.isEmpty()) it.visibility = View.GONE
                                it.contentText = bean.productDate
                            }
                            .with<ItemLayout>(R.id.il_batch) {
                                if (bean.productBatch.isEmpty()) it.visibility = View.GONE
                                it.contentText = bean.productBatch
                            }
                            .with<ItemLayout>(R.id.il_remark) {
                                if (bean.remark.isEmpty()) it.visibility = View.GONE
                                it.contentText = bean.remark
                            }
                            .with<ImageLayout>(R.id.layout_image) {
                                it.setImageList(bean.formatPathList)
                            }
                            .clicked(R.id.tv_delete) {
                                messageDialog(msg = "是否删除？") { _, _ ->
                                    HttpCall.get(UrlConfig.PRODUCT_DETAIL_DELETE)
                                            .addParam("id", bean.id)
                                            .enqueue(object : DataDialogHttpCallback<Int>(this@ProductInfoEditActivity) {
                                                override fun onSuccess(data: Int?, resultType: ResultType) {
                                                    adapter.remove(position)
                                                    adapter.notifyItemRangeChanged(position, adapter.getDataList().size - position)
                                                }
                                            })
                                }
                            }
                            .clicked(R.id.tv_edit) {
                                ActivityResult.with(this@ProductInfoEditActivity)
                                        .targetActivity(ProductDetailEditActivity::class.java)
                                        .putInt(Constants.ID, productInfoId)
                                        .putString(Constants.TITLE, productName)
                                        .putSerializable(Constants.DATA, bean)
                                        .onResult {
                                            val data = it?.getSerializableExtra(Constants.DATA)
                                            adapter.remove(position)
                                            adapter.addData(position, data)
                                        }
                            }
                }
                .attachTo(recycler_view_detail)
                .setDataList(dataList)
                .addFooter(this, R.layout.list_item_add) { slimAdapter, view ->
                    view.onClick {
                        if (productInfoId == -1) {
                            toast("请保存基本信息")
                            return@onClick
                        }
                        ActivityResult.with(this@ProductInfoEditActivity)
                                .targetActivity(ProductDetailEditActivity::class.java)
                                .putInt(Constants.ID, productInfoId)
                                .putString(Constants.TITLE, productName)
                                .onResult {
                                    val data = it?.getSerializableExtra(Constants.DATA) as ProductItemBean?
                                    if (data != null) {
                                        adapter.addData(data)
                                        dataList.add(data)
                                    }
                                }

                    }
                }

    }

    private fun price() {
        val calendar = Calendar.getInstance()
        val date = sdf.format(calendar.time)
        dataList.add(KeyValue(date, ""))
        val adapter = SlimAdapter.creator()
        adapter
                .register<KeyValue>(R.layout.list_item_product_price) { injector, bean, position ->
                    injector.visibility(R.id.tv_label, if (position == 0) View.VISIBLE else View.INVISIBLE)
                            .text(R.id.tv_date, "$date -> ")
                            .text(R.id.tv_price, bean.value)
                            .clicked(R.id.tv_date) {
                                TimeFragment.Builder(this@ProductInfoEditActivity)
                                        .setDate(calendar)
                                        .setDisplayStyle(booleanArrayOf(true, true, true, false, false, false))
                                        .setOnlyCenterLabel(false)
                                        .setSubmitListener(object : OnTimeSelectedListener {
                                            override fun onTimeSelect(date: Date, v: View) {
                                                tv_date.text = "${sdf.format(date)} -> "
                                                calendar.time = date
                                            }
                                        })
                                        .show()
                            }
                            .clicked(R.id.iv_delete) {
                                for (i in 0 until recycler_view_price.childCount - 1) {
                                    val view = recycler_view_price.getChildAt(i)
                                    val text = view.find<EditText>(R.id.tv_price).text?.toString()
                                    adapter.getDataList<KeyValue>()[i].value = text.orEmpty()
                                }
                                val priceBean = adapter.getDataList<KeyValue>()[position]
                                messageDialog(msg = "是否删除\"${priceBean.key} -> ${priceBean.value}\"?") { _, _ ->
                                    adapter.setDataList(adapter.getDataList<KeyValue>())
                                    adapter.remove(position)
                                    adapter.notifyItemRangeChanged(position, adapter.getDataList().size - position)
                                }

                            }
                }
                .attachTo(recycler_view_price)
                .setDataList(dataList)
                .addFooter(this, R.layout.list_item_add) { slimAdapter, view ->
                    view.onClick {
                        for (i in 0 until recycler_view_price.childCount - 1) {
                            val recyclerView = recycler_view_price.getChildAt(i)
                            val text = recyclerView.find<EditText>(R.id.tv_price).text?.toString()
                            adapter.getDataList<KeyValue>()[i].value = text.orEmpty()
                            if (text.isNullOrBlank()) {
                                toast("请补充价格")
                                return@onClick
                            }
                        }
                        adapter.addData(KeyValue(date, ""))
                    }
                }
    }


    fun commit() {
        var strPrice = ""
        for (i in 0 until recycler_view_price.childCount - 1) {
            val view = recycler_view_price.getChildAt(i)
            val date = view.find<TextView>(R.id.tv_date).text?.toString()
            val price = view.find<EditText>(R.id.tv_price).text?.toString()
            if (!price.isNullOrEmpty()) {
                strPrice += "${date}${price};"
            }
        }
        if (!strPrice.isEmpty())
            strPrice = strPrice.substring(0, strPrice.length - 1)


        val params = HttpParams()
        val url = if (productInfoId != -1) {
            val netFileList = layout_image.netFileList()
            if (!netFileList.isNullOrEmpty()) {
                val str = netFileList.joinToString(",")
                params.put("netImageStr" to str)
            }
            params.put("id", productInfoId)
            UrlConfig.PRODUCT_INFO_UPDATE
        } else
            UrlConfig.PRODUCT_INFO_ADD
        params.put(
                "userId" to "",
                "productType" to il_type.contentText,
                "nation" to il_nation.contentText,
                "company" to il_company.contentText,
                "factoryNo" to il_factory.contentText,
                "productName" to il_product_name.contentText,
                "productNo" to il_product_no.contentText,
                "specification" to il_specification.contentText,
                "priceTrend" to strPrice,
                "remark" to il_remark.contentText
        )

        HttpCall.post(url)
                .addParams(params)
                .addFiles("images[]", layout_image.localFileList().map { File(it) })
                .enqueue(object : DataDialogHttpCallback<ProductBean>(this) {
                    override val mIsOnSuccessToast: Boolean
                        get() = true

                    override fun onSuccess(data: ProductBean?, resultType: ResultType) {
                        data?.let {
                            productInfoId = it.id
                            productName = it.factoryNo + it.productName
                            top_bar.tv_top_bar_right.text = "编辑"
                            layout_edit.visibility = View.GONE
                            layout_display.visibility = View.VISIBLE
                            initInfo(it)
                        }
                    }
                })
    }
}